<?php
/*
Plugin Name: Easy Polling Plugin 
Plugin URI: http://pollingplugin.com/
Description: WordPress polling system with capability for Social Polling and BuddyPress polling.
Version: 2.5
Author: MYO
Author URI: http://www.make-your-offer.com
*/

    #} Hooks
    
    #) Translations
	function polling__languageInit() {
		load_plugin_textdomain( 'myopolling', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
	}
	add_action('plugins_loaded', 'polling__languageInit');

    #} Install/uninstall
    register_activation_hook(__FILE__,'myo_polling__install');
    register_deactivation_hook(__FILE__,'myo_polling__uninstall');
    
    #} general
    add_action('init', 'myo_polling__init');
    add_action('admin_menu', 'myo_polling__admin_menu'); #} Initialise Admin menu
    
    

	#} Initial Vars
	global $myo_polling_db_version;
	$myo_polling_db_version             	   = "1.0";
	$myo_polling_version           		       = "2.5";
	$myo_polling_activation                    = '';


	#} Urls
    global $myo_polling_urls;
    $myo_polling_urls['home']   	   	 = 'http://pollingplugin.com/';
    $myo_polling_urls['docs']     		 = plugins_url('/documentation/index.html',__FILE__);
	$myo_polling_urls['forum']      	 = 'http://epicplugins.com/support-forums/';
    $myo_polling_urls['updateCheck']	 = 'http://www.epicplugins.com/api/';
	$myo_polling_urls['regCheck']		 = 'http://www.epicplugins.com/registration/';
	$myo_polling_urls['subscribe'] 		 = "http://eepurl.com/tW_t9";
	
	#} Page slugs
    global $myo_polling_slugs;
    $myo_polling_slugs['config']           = "myo_polling-plugin-config";
    $myo_polling_slugs['settings']         = "myo_polling-plugin-settings";

	#} Install function
	function myo_polling__install(){

    #} Default Options

    add_option('myo_polling_ip','yes','','yes');
	add_option('myo_flush','no','','yes');
	add_option('myo_polling_version','2.0','','yes');
	add_option('myo_logged','no','','yes');   //require users to be logged in to vote
	myo_polling_install();
	add_option('pollingshared','no','','yes'); 
		
	$current_user = wp_get_current_user();    //email the current user rather than admin info more likely to reach a human email 
	$userEmail = $current_user->user_email;
	$userName =  $current_user->user_firstname;
	$LastName =  $current_user->user_lastname;
	$plugin = 'PollingPlugin';
			
	if(get_option('pollingshared') == 'no'){    //only send them an install email once
			polling_sendReg($userEmail,$userName,$plugin);
	}  
	
	
 
	}
	
	
	global $myo_polling_db_version;
	$myo_polling_db_version = "1.0";

   function myo_polling_install() {
   global $wpdb;
   global $myo_polling_db_version;

   $table_name = $wpdb->prefix . "myo_ip";
      
   $sql = "CREATE TABLE $table_name (
	  id mediumint(9) NOT NULL AUTO_INCREMENT,
	  myo_polling_id mediumint(9) NOT NULL,
	  myo_polling_option mediumint(9) NOT NULL,
	  myo_polling_ip text NOT NULL,
	  myo_fb mediumint(9) NOT NULL,
	  myo_fb_name text NOT NULL,
	  UNIQUE KEY id (id)
	    );";

	   require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	   dbDelta($sql);
	 
	   add_option("myo_polling_db_version", $myo_polling_db_version);
	   
	  
	   
	}

	#} Uninstall
	function myo_polling__uninstall(){
	    
	    #} Removes initial settings, leaves config intact for upgrades.
	    delete_option("myo_polling_db_version");
	    delete_option("myo_polling_version");
	    delete_option("myo_polling_activation");
	    
	}

    function easy_custom(){
    #} Custom post type
    $labels = array(
                'name' => _x('Polls', 'post type general name'),
                'singular_name' => _x('Poll', 'post type singular name'),
                'add_new' => _x('Add New Poll', 'myo_polling'),
                'add_new_item' => __('Add New Poll'),
                'edit_item' => __('Edit Poll'),
                'new_item' => __('New Poll'),
                'view_item' => __('View Polls'),
                'search_items' => __('Search Polls'),
                'not_found' =>  __('No Polls found'),
                'not_found_in_trash' => __('No Polls found in Trash'),
                'parent_item_colon' => '',
                'menu_name' => 'Easy Polls'
            );
    $args = array(
                'labels' => $labels,
                'public' => true,
                'publicly_queryable' => true,
                'show_ui' => true,
                'show_in_menu' => true,
                'query_var' => true,
                'rewrite' => array( 'slug' => 'myo_polling','with_front' => FALSE ),
                'capability_type' => 'post',
                'has_archive' => true,
                'hierarchical' => false,
                'menu_icon' => plugins_url('i/polls.png',__FILE__),
                'menu_position' => 5,
                'supports' => array( 'title')
            );
    #} Register it
    register_post_type('myo_polling',$args);
    }


#} Initialisation - enqueueing scripts/styles
function myo_polling__init(){
  
    global $myo_polling_slugs, $myo_polling_taxonomy; #} Req
    
    #} Admin & Public
    wp_enqueue_script("jquery");
    wp_enqueue_script( 'jquery-form',array('jquery')); 
    wp_enqueue_script('myo-polling-ajax',plugins_url('/js/myo-polling.js',__FILE__),array('jquery'));
	


    wp_localize_script( 'myo-polling-ajax', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    wp_enqueue_style('myo-polling-css', plugins_url('/css/myo-polling.css',__FILE__) );

    #} Admin only
    if (is_admin()) {
	wp_enqueue_style( 'farbtastic' );
    wp_enqueue_script( 'farbtastic' );
    wp_enqueue_script('myo-polling-ajax-admin',plugins_url('/js/myo-polling-admin.js',__FILE__),array('jquery','farbtastic'));
	wp_enqueue_style('mysmashCSSADM', plugins_url('/css/MySmashAdmin.css',__FILE__) );

    #} Admin CSS
    wp_enqueue_style('myo-polling-admin-css', plugins_url('/css/myo-polling-admin.css',__FILE__) );

    }
	
   easy_custom();
   if(get_option('myo_flush') == 'no'){
   flush_rewrite_rules();  //flushes rewrite rules
   update_option("myo_flush", 'yes');
   }
    


}

#} Add le admin menu
function myo_polling__admin_menu() {

    global $myo_polling_slugs,$myo_polling_menu; #} Req
    
    $myo_polling_menu = add_menu_page( 'My Polling Menu', 'Easy Poll Admin', 'manage_options', $myo_polling_slugs['config'], 'myo_polling_menu', plugins_url('i/polls.png',__FILE__));
     add_submenu_page( $myo_polling_slugs['config'], 'Settings', 'Settings', 'manage_options', $myo_polling_slugs['settings'] , 'myo_polling_pages_settings' );
	 do_action('myo_fb_hook');
	 
}


#}Settings
function myo_polling_pages_settings() {
    
    global $wpdb;    #} Req
    
    if (!current_user_can('manage_options'))  {
        wp_die( __('You do not have sufficient permissions to access this page.') );
    }
    
    
?><div id="sgpBod">
          <div class='myslogo'><?php echo '<img src="' .plugins_url( 'i/logo.png' , __FILE__ ). '" > ';   ?></div>
        <div class='mysearch'>
        	
        <?php myo_polling_header(); ?>
            
                
         <?php
         	if(isset($_GET['save'])){ 
             if ($_GET['save'] == "1"){
                myo_polling_html_save_settings();
             }
		    }
            if(!isset($_GET['save'])){
                myo_polling_html_settings();
            }
    ?></div>
</div>
<?php
}


function myo_polling_html_settings(){
        
    global $wpdb, $myo_polling_slugs;  #} Req
    
    $myoConfig = array();
    $myoConfig['trans_id'] 		   =           get_option('myo_polling_trans_id');    
    $myoConfig['myo_polling_ip']   =           get_option('myo_polling_ip');    
	$myoConfig['myo_logged']	   =           get_option('myo_logged'); 

    
    ?>
    

     <form action="?page=<?php echo $myo_polling_slugs['settings']; ?>&save=1" method="post">
     <div class="postbox">
     <h3><label>General settings</label></h3>
     
     <table class="form-table" width="100%" border="0" cellspacing="0" cellpadding="6">
         
        <tr valign="top">
            <td width="25%" align="left"><strong>item purchase code:</strong></td>
            <td align="left"><input id=pstrans_id name=myo_polling_trans_id type="text" placeholder="item purchase code" size="20" value = '<?php echo $myoConfig['trans_id']; ?>' /><br><i>This is the purchase code contained in your License Certificate on CodeCanyon</i></td>
        </tr>

        <tr valign="top">
                        <td width="25%" align="left"><strong>One vote per IP:</strong></td>
                        <?php if($myoConfig['myo_polling_ip'] == 'yes'){ ?>
                        <td align="left">
                            <input type="radio" name="myo_polling_ip" value="yes" checked> Yes
                            <input type="radio" name="myo_polling_ip" value="no"> No
                            <br><i>Restrict the votes to one per IP address</i>
                        </td>
                        <?php }else{ ?>
                         <td align="left">
                            <input type="radio" name="myo_polling_ip" value="yes"> Yes
                            <input type="radio" name="myo_polling_ip" value="no" checked> No
                            <br><i>Restrict the votes to one per IP address</i>
                        </td>
                        <?php } ?>
         </tr>
         
         <tr valign="top">
                        <td width="25%" align="left"><strong>Require users to be logged in to vote:</strong></td>
                        <?php if($myoConfig['myo_logged'] == 'yes'){ ?>
                        <td align="left">
                            <input type="radio" name="myo_logged" value="yes" checked> Yes
                            <input type="radio" name="myo_logged" value="no"> No
                             <br><i>Require users to be logged in to vote (for non <a href = "http://codecanyon.net/item/wordpress-social-polling-plugin/3750798?ref=mikemayhem3030" target = "_blank">Facebook polls</a>)</i>             
                        </td>
                        <?php }else{ ?>
                         <td align="left">
                            <input type="radio" name="myo_logged" value="yes"> Yes
                            <input type="radio" name="myo_logged" value="no" checked> No
                            <br><i>Require users to be logged in to vote (for non <a href = "http://codecanyon.net/item/wordpress-social-polling-plugin/3750798?ref=mikemayhem3030" target = "_blank">Facebook polls</a>)</i>
                        </td>
                        <?php } ?>
         </tr>
      
    </table>
    <p id="footerSub"><input class = "button-primary" type="submit" value="Save settings" /></p>
    </form>
</div>

<?php }



#} Save options changes
function myo_polling_html_save_settings(){
    
    global $wpdb;  #} Req
    
    $myoConfig = array();
    $myoConfig['myo_polling_ip'] 	=           $_POST['myo_polling_ip'];
    $myoConfig['trans_id'] 			=           $_POST['myo_polling_trans_id'];
	$myoConfig['myo_logged'] 		=	        $_POST['myo_logged'];

    
    #} Save down
    update_option("myo_polling_ip", $myoConfig['myo_polling_ip']);
    update_option("myo_polling_trans_id", $myoConfig['trans_id']);
	update_option("myo_logged", $myoConfig['myo_logged']);


    #} Msg
    myo_polling_html_msg(0,"Saved options");
    
    #} Run standard
    myo_polling_html_settings();
    
}






function myo_polling_checkForMessages(){
    
    global $myo_polling_urls;

    # First deal with legit purchases
    if (isset($_GET['legit'])){
        
        # Update
        update_option('myo_polling_myo_firstLoadMsg',1);
        
        #} Set this here
        $flFlag = 1;
        
    } else $flFlag = get_option('myo_polling_myo_firstLoadMsg');
    
    
    
    if (empty($flFlag)) {
        
        myo_polling_html_msg(2,'<div class="sgThanks">
            <h3>Thank you for installing the Easy Polling Plugin, only available on CodeCanyon!</h3>
            <p>This license entitles you to use the Easy Polling Plugin on a single WordPress install.</br>
            </p>
                        
            <p>Its Easy to get started, you can work it out for yourself below or read the <a href="'.$myo_polling_urls['docs'].'" target="_blank">Easy Polling Support Manual</a>.<br />To keep up to date with Easy Polling Plugin follow us on <a href="http://codecanyon.net/user/mikemayhem3030/follow/" target="_blank">CodeCanyon</a></p>
        
            <div class="sgButtons">
                <a class="buttonG" href="?page=myo_polling-plugin-config&legit=true">I have a License</a>
                <a class="buttonBad" href="http://codecanyon.net/item/pics-mash-image-rating-tool/3256459">I need a License</a>
            </div>
                    
            <div class="clear"></div>
        </div>');
        
    }
    
}

#} Options page
function myo_polling_menu() {
    
    global $wpdb, $myo_polling_urls, $myo_polling_version,$myo_polling_slugs;    #} Req
    // add database pointer
    
    if (!current_user_can('manage_options'))  {
        wp_die( __('You do not have sufficient permissions to access this page.') );
    }
    ?>
    <div id="sgpBod">
       <div class='myslogo'><?php echo '<img src="' .plugins_url( 'i/logo.png' , __FILE__ ). '" > ';   ?></div>
        <div class='mysearch'>
            
            <?php myo_polling_header(); ?>
            
            <?php myo_polling_checkForMessages(); ?>

               <div class="postbox-container" id="main-container" style="width:75%;">
            <div class="postbox">
           <h3 style="text-align:center"><label>Welcome to the Easy Polling Plugin</label></h3>
                <div class="inside">
                    <p style="text-align:center"><strong>Welcome to Easy Polling 2.5</strong>: the Ultimate WordPress Polling Plugin If you want to vote on future features or discover more cool plugins, check out the <br/><a href="http://epicplugins.com" target="_blank">epic plugins site</a>!</p>
                    <div id="SocialGalleryOptions">
                        <div><a href="admin.php?page=<?php echo $myo_polling_slugs['settings']; ?>" class="SocialGalleryOB">Settings</a></div>
                        <div><a href="edit.php?post_type=myo_polling" class="SocialGalleryOB">Manage Polls</a></div>
                        <div><a href="admin.php?page=<?php echo $myo_polling_urls['home']; ?>" class="SocialGalleryOB">Demo Site</a></div>
                    </div>
                    <div style="clear:both"></div>
                </div>
            </div>
           
            
            <div class="postbox">
                <h3 style="padding:8px;"><label><?php _e('Easy Polling News'); ?></label></h3>
                <div class="inside">
                	<?php polling_retrieveNews(); ?>
                </div>
            </div>  
   </div>

    <div class="postbox-container" id="side-container" style="width:24%;margin-left:1%">
            <div class="postbox">
                <h3 style="padding:8px;"><label><?php _e('Share the love'); ?></label></h3>
                <div class="inside">
                	<p>This plugin has been developed with love & effort, it's a work in progress and I really appreciate all of the contribution you guys make to it. Thank you!</p>
                	
                    <!-- <a href="codecanyon.net/item/social-gallery-wordpress-photo-viewer-plugin/2665332?ref=stormgate" target="_blank">Rate it 5 stars on Code Canyon</a><br /> -->
                  
                    <div  style="text-align:center;margin-top:12px"><strong>Share Easy Polling:</strong></div>
                    <div class="socialGalleryShareBox">
	                    <a href="http://www.facebook.com/sharer.php?s= 100&amp;p[title]=Easy Polling - The Ultimate WordPress Polling Plugin&amp;p[url]=http://pollingplugin.com/&amp;p[summary]=Easy Polling helps you ask your visitors polls. A Must Have plugin for all WordPress users."target="_blank"><img src="<?php echo plugins_url('/i/fbshare.png',__FILE__); ?>" alt="" title="Share on Facebook" /></a>
	        	     	<a href="http://twitter.com/home?status=I Recommend You Easy Polling for WordPress!! http://pollingplugin.com/" target="_blank"><img src="<?php echo plugins_url('/i/tweet.png',__FILE__); ?>" alt="" title="Share this on Twitter" /></a>
					 	<a href="http://www.linkedin.com/shareArticle?mini=true&url=http://pollingplugin.com/&title=Easy Polling for WordPress&source=PicsMash" target="_blank"><img src="<?php echo plugins_url('/i/linkedin.png',__FILE__); ?>" alt="" title="Share this on LinkedIn" /></a>
						<a href="https://plus.google.com/share?url=http://pollingplugin.com/" target="_blank"><img src="<?php echo plugins_url('/i/gp.png',__FILE__); ?>" alt="" title="Share this on Google+1" /></a>
         			</div>
                </div>
            </div>
   </div>

   <div class="postbox-container" id="side-container" style="width:24%;margin-left:1%">
            <div class="postbox">
                <h3 style="padding:8px;"><label><?php _e('Other Plugins'); ?></label></h3>
                <div class="inside">
					<table>
						<tr>
							<td><a href = "http://codecanyon.net/item/wordpress-social-polling-plugin/3750798?ref=mikemayhem3030" target = "_blank"><img src = "http://2.s3.envato.com/files/45080320/SP.png"/></a></td>
							<td style = "padding:3px"><a href = "http://codecanyon.net/item/wordpress-social-polling-plugin/3750798?ref=mikemayhem3030?ref=mikemayhem3030" target = "blank">Social Polling Plugin</a> is the future of website polling. Once someone votes on a poll it posts out to the voters news feed to help bring in more voters!
								</td>
						</tr>
												<tr>
							<td><a href = "http://codecanyon.net/item/dilemma-wordpress-plugin/3377683?ref=mikemayhem3030" target = "_blank"><img src = "http://0.s3.envato.com/files/40545635/dilemmaicon.png"/></a></td>
							<td style = "padding:3px"><a href = "http://codecanyon.net/item/dilemma-wordpress-plugin/3377683?ref=mikemayhem3030?ref=mikemayhem3030" target = "blank">Dilemma!</a> the Ultimate Yes/No Plugin for WordPress. Ask your visitors engaging Dilemmas!
								</td>
						</tr>
					</table>
                </div>
            </div>
	 
	 <div style = 'clear:both'></div>
	 
	 </div>            

     </div>


</div>
<?php
}

#} Retrieves updated news.
function polling_retrieveNews(){

				global $tweety_urls;
                include_once(ABSPATH . WPINC . '/feed.php');
                add_filter( 'wp_feed_cache_transient_lifetime' , 'pol_feed_cache' );
				$url = 'http://pollingplugin.com/feed/';
                $rss = fetch_feed($url);
                remove_filter( 'wp_feed_cache_transient_lifetime' , 'pol_feed_cache' );
                
                if (!is_wp_error( $rss ) ) {
					
					$maxitems = $rss->get_item_quantity(5); 
                    $rss_items = $rss->get_items(0, $maxitems); 
					
				} ?>
                
                <ul>
                    <?php 
					if ($maxitems == 0) 
						echo '<li>No News (is this good news?)</li>';
                    else 
						foreach ( $rss_items as $item ) : ?>
                    <li>
                        <a href='<?php echo esc_url( $item->get_permalink() ); ?>' target = '_blank'
                        title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
                        <?php echo  $item->get_title() ; ?></a><br/>
                        <?php echo  $item->get_description() ; ?>
                    </li>
                    <?php endforeach; ?>
                </ul>
                
                <?php
	
}

function pol_feed_cache( $seconds )
			{
			  // change the default feed cache recreation period to 2 hours
			  return 7200;
			}



add_action( 'wp_ajax_nopriv_myo_polling_vote', 'myo_polling_vote' );
add_action( 'wp_ajax_myo_polling_vote', 'myo_polling_vote' );

function myo_polling_vote(){
	global $wpdb;
	$wpdb->myo_ip   = $wpdb->prefix . 'myo_ip';
	
	$IP = get_option('myo_polling_ip');
	$poll = (int)$_POST['poll'];
    $option = (int)$_POST['option'];

	if($IP == 'yes'){
		$postid = $_POST['poll'];	
		$ip	= "'".$_SERVER['REMOTE_ADDR']."'";
		$query = "SELECT myo_polling_id FROM $wpdb->myo_ip WHERE myo_polling_ip = $ip AND myo_polling_id = $postid";
		$al = $wpdb->get_var($query);
		if($al == NULL){
			$query = "INSERT INTO $wpdb->myo_ip ( myo_polling_id , myo_polling_ip, myo_polling_option ) VALUES ( $postid, $ip, $option )";
			$wpdb->query($query);
		}
	}
	

	
    $votes = get_post_meta($poll,'myo-votes',true);
	$options = get_post_meta($poll,'myo-options',true);
	
    $votes_array = explode(",",$votes);
	$option_array = explode(",",$options);
   
    $votes_array[$option] = $votes_array[$option]+1;
	$total_votes = array_sum($votes_array);
	$votes = implode(",",$votes_array);
	update_post_meta($poll,'myo-votes',$votes);
   
	$response['poll'] = $poll;
	$response['option'] = $option_array;
	$response['votes'] = $votes_array;
	$response['total'] = $total_votes;
	$response['chosen'] = $option;
    
    echo json_encode($response);
  
	// IMPORTANT: don't forget to "exit"
	exit;
}

function myo_polling_header(){

    global $myo_polling_urls;
    ?>
     
    <div id="fb-root"></div>
    <script>(function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=438275232886336";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));</script>

    <?php
    //build the twitter text tweet
        $URL = $myo_polling_urls['home'];
        $siteURL = get_site_url();
        $PicsM = "http://pollingplugin.com/";
        $text = "I love " . $PicsM;
        $hash = "#myo_polling";
        $QP = "?url=".$URL."&text=".$text."&hashtags=".$hash;
    ?>
    
	
	
    <?php

        $img = "http://3.s3.envato.com/files/40545636/myo_pollingpreview.jpg";
        echo "<a href='http://pinterest.com/pin/create/button/?url=$URL&media=$img&description=Description' class='pin-it-button' count-layout='horizontal'><img border'0' src='//assets.pinterest.com/images/PinExt.png' title='Pin It' /></a>";
    ?>

    <div class="fb-like" data-href="http://myo_pollingplugin.com/" data-send="true" data-width="360" data-show-faces="false" data-font="arial"></div>

    <?php
	$home = $myo_polling_urls['home'];
	$docs = $myo_polling_urls['docs'];
	$forum =$myo_polling_urls['forum'];
	$subs = $myo_polling_urls['subscribe'];
        echo "<div id = 'ps-links' style = 'padding-top:1%;padding-bottom:1%'><ul style = 'display:inline'>
        <li style = 'display:inline;padding-right:1%'><a href = '$home'>Demo Site</a></li>
        <li style = 'display:inline;padding-right:1%'><a href = '$docs'>Documentation</a></li>
        <li style = 'display:inline;padding-right:1%'><a href = '$forum'>Support Forum</a></li>
        <li style = 'display:inline;padding-right:1%'><a href = '$subs'>Subscribe to the EPIC mailing list</a></li>
        <li style = 'display:inline;padding-right:1%'><a href='mailto:mikemayhem3030@gmail.com?Subject=Hi%20Mike You Rock!'>Contact the developer</a></li>
        </ul></div>";

}


#} Outputs HTML message
function myo_polling_html_msg($flag,$msg,$includeExclaim=false){
    
    if ($includeExclaim){ $msg = '<div id="sgExclaim">!</div>'.$msg.''; }
    
    if ($flag == -1){
        echo '<div class="sgfail wrap">'.$msg.'</div>';
    }
    if ($flag == 0){ ?>
        <div id="message" class="updated fade below-h2"><p><strong>Settings saved!</strong></p></div>
    <?php }
    if ($flag == 1){
        echo '<div class="sgwarn wrap">'.$msg.'</div>';
    }
    if ($flag == 2){
        echo '<div class="sginfo wrap">'.$msg.'</div>';
    }
    if ($flag == 666){ ?>
        <div id="message" class="updated fade below-h2"><p><strong><?php echo $msg; ?>!</strong></p></div>
    <?php }
}



function myo_poll( $atts ) {
	extract( shortcode_atts( array(
		'poll' => 'true',
		'perc' => 'true',
		'type' => 'true'
	), $atts ) );
    
    global $wp_query,$paged,$post,$wp,$wpdb;
    $wpdb->myo_ip   = $wpdb->prefix . 'myo_ip';

	$ip	= "'".$_SERVER['REMOTE_ADDR']."'";  //for IP logging
	
	$IP = get_option('myo_polling_ip');
	$added = NULL; 
	if($IP == 'yes'){
	$querystr = "SELECT myo_polling_id FROM $wpdb->myo_ip WHERE myo_polling_ip = $ip AND myo_polling_id = $poll";
    $added = $wpdb->get_col($querystr);
	$querystr = "SELECT myo_polling_option FROM $wpdb->myo_ip WHERE myo_polling_ip = $ip AND myo_polling_id = $poll";
    $chosen = $wpdb->get_col($querystr);
	
	}
	
	
	
	
   if($type == 'true'){
   	$type = get_post_meta($post->ID,'myo-type',true);
   }
   if($perc == 'true'){
   	$perc = get_post_meta($post->ID,'myo-display',true);
   }
	
    $content = null;  
    ob_start();

    if ( is_user_logged_in() ) { ?>
	<script type="text/javascript">var loggedin = 'yes';</script>

	<?php }else{
		  
		if(get_option('myo_logged') == 'yes'){ ?>
			<script type="text/javascript">var loggedin = 'no';</script>
			<script type="text/javascript">	var loginurl = '<?php echo wp_login_url();?>';</script>
			<script type="text/javascript">	var registerurl = '<?php wp_register('', ''); ?>';</script>
		<?php }else{ ?>
			<script type="text/javascript">var loggedin = 'yes';</script>	
		<?php } ?>
	
	
<?php   } ?>

	<script type="text/javascript">var myoperc = '<?php echo $perc; ?>';</script>
          
	<?php
	$mtitle = 'yes';
	$mtitle = get_post_meta($poll,'myo-title',true);
	
  if($mtitle == 'yes'){
   echo "<div class = 'rtn-poll-title'><h5>". get_the_title($poll) . "</h5></div>";	
  }
   $poll_options = get_post_meta($poll,'myo-poll-options',true);
   $options = get_post_meta($poll,'myo-options',true);
   $colors = get_post_meta($poll,'myo-colors',true);
   
   $opts = explode(",",$options);
   if($opts[0] == NULL){
   	
   }else{
   $cls = explode(",",$colors);
   
   $votes = get_post_meta($poll,'myo-votes',true);
   $votes_array = explode(",",$votes);
   $find = -1; $top = 0; $i = 0; foreach ($votes_array as $n){ if ($n > $top){$find = $i; $top = $n;} $i++;}
	
   	
   
	$total_votes = array_sum($votes_array);
   
	echo "<div class = 'rtn-holder'><div id = 'myo-poll-$poll-main' class = 'myo-poll-main'>";
	
	if($added != NULL && $IP == 'yes'){
	$myov = $chosen[0];	
	$top = $find;	
		
		if($type == 'bar'){
		$i = 0;
		while($i < $poll_options){
			if($total_votes == 0){
				$percent = 0;
			}else{
				$percent = round(100*($votes_array[$i]/$total_votes),0);
			}
			if($i == $top){
				$topclass = 'myo-poll-top';
			}else{
				$topclass = "";
			}
			if($i == $myov){
				$voteclass = 'myo-poll-my-vote';
			}else{
				$voteclass = "";
			}
			
			$color = $cls[$i];
			if($color[0] != '#'){
				$color = "#" . $color;
			}
			
			echo "<div class = '$topclass $voteclass myo-poll-holder-$type' id = 'myo-poll-holder-$poll-$i' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'yes' data-myo-poll-id = '$poll' >
			<div id = 'myo-poll-$poll-$i' class = 'gradient myo-poll-$poll  myo-poll-$type myo-poll-#$color-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'yes' data-myo-poll-id = '$poll' style = 'background:$color;width:$percent%'></div>";
			echo "<div id = 'myo-poll-$poll-votes-$i' class = 'myo-poll-votes myo-poll-$poll myo-poll-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'yes' data-myo-poll-id = '$poll' >
			$opts[$i]";
			if($perc == "yes"){
				echo " " . $percent . "%";
			}else{
				echo " " . $votes_array[$i] . " votes";
			}
			echo "</div>
			</div>";
	
			$i++;
		}
		}
		if($type == "box"){
		$i = 0;
		while($i < $poll_options){
			if($total_votes == 0){
				$percent = 0;
			}else{
				$percent = round(100*($votes_array[$i]/$total_votes),0);
			}
			if($i == $top){
				$topclass = 'myo-poll-top';
			}else{
				$topclass = "";
			}
			if($i == $myov){
				$voteclass = 'myo-poll-my-vote';
			}else{
				$voteclass = "";
			}
			
			$color = $cls[$i];
			if($color[0] != '#'){
				$color = "#" . $color;
			}
			
			echo "<div class = '$topclass $voteclass myo-poll-holder-$type-$poll myo-poll-holder-$type' id = 'myo-poll-holder-$poll-$i' data-myo-poll-id = '$poll' data-myo-option = '$i' data-myo-clicked = 'yes' style = 'border-bottom-color:$color;border-bottom-style:solid'>";
			
			echo "<div id = 'myo-poll-$poll-$i' class = 'myo-poll-$poll myo-poll-$type myo-poll-$color-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'yes' data-myo-poll-id = '$poll' style = 'background:$color;'><div class = 'rtn-option-1'><div class = 'rtn-option-2'>$opts[$i]</div></div></div>";
			if($type == "box"){
				if($perc == 'no'){
				echo "<div id = 'myo-poll-$poll-box-$i-votes' class = 'myo-poll-box-votes' style = 'color:$color'>$votes_array[$i]</div>
				<div class = 'myo-vote-me myo-vote-me-$poll-$i' data-myo-poll-id = '$poll' style = 'color:$color;'>vote</div>
				<div id = 'myo-box-votes-$poll-$i' style = 'color:#$cls[$i]'>votes</div>";
				}else{
				echo "<div id = 'myo-poll-$poll-box-$i-votes' class = 'myo-poll-box-votes' style = 'color:$color'>$percent%</div>
				<div class = 'myo-vote-me myo-vote-me-$poll-$i' data-myo-poll-id = '$poll' style = 'color:$color;'>vote</div>
				<div id = 'myo-box-votes-$poll-$i' style = 'color:$color'></div>";				
				}
			}
			echo "</div><div class = 'rtn-poll-votes'><div id = 'myo-poll-$poll-votes-$i' class = 'myo-poll-votes'></div></div>";
	
			$i++;
			}
		}
		echo "<div class = 'rtn-bottom'></div>";	
		
		
		echo "</div>";
		echo "<div id = 'myo-poll-$poll-total'><b>Total </b>$total_votes votes</div>";
		echo "</div>";
	
	
	}else{ 
		if($type == 'bar'){
		$i = 0;
		while($i < $poll_options){
				$color = $cls[$i];
			if($color[0] != '#'){
				$color = "#" . $color;
			}
			
			echo "<div class = 'myo-poll-holder-$type' id = 'myo-poll-holder-$poll-$i' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'no' data-myo-poll-id = '$poll'>
			<div id = 'myo-poll-$poll-$i' class = 'gradient myo-poll-$poll  myo-poll-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'no' data-myo-poll-id = '$poll' style = 'background:$color'></div>";
			echo "<div id = 'myo-poll-$poll-votes-$i' class = 'myo-poll-votes myo-poll-$poll myo-poll-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'no' data-myo-poll-id = '$poll'>$opts[$i]</div>
			</div>";
	
			$i++;
		}
		}
		if($type == "box"){
		$i = 0;
		while($i < $poll_options){
				$color = $cls[$i];
			if($color[0] != '#'){
				$color = "#" . $color;
			}
			
			echo "<div class = 'myo-poll-holder-$type-$poll myo-poll-holder-$type' id = 'myo-poll-holder-$poll-$i' data-myo-poll-id = '$poll' data-myo-option = '$i' data-myo-clicked = 'no' style = 'border-bottom-color:$color;border-bottom-style:solid'>
			<div id = 'myo-poll-$poll-$i' class = 'myo-poll-$poll myo-poll-$type' data-myo-perc = '$perc' data-myo-option = '$i' data-myo-clicked = 'no' data-myo-poll-id = '$poll' style = 'background:$color;'><div class = 'rtn-option-1'><div class = 'rtn-option-2'>$opts[$i]</div></div></div>";
			if($type == "box"){
				echo "<div id = 'myo-poll-$poll-box-$i-votes' class = 'myo-poll-box-votes' style = 'color:$color'></div>
				<div class = 'myo-vote-me myo-vote-me-$poll-$i' data-myo-poll-id = '$poll' style = 'color:$color;'>vote</div>
				<div id = 'myo-box-votes-$poll-$i' style = 'color:$color'></div>";
			}
			echo "</div><div id = 'myo-poll-$poll-votes-$i' class = 'myo-poll-votes'></div>";
	
			$i++;
			}
		}

	echo "</div>";
		echo "<div id = 'myo-poll-$poll-total'></div></div>";


	
	}

}




    $content = ob_get_contents();
    ob_end_clean();
    return $content;
    
}

add_shortcode("myo_poll", "myo_poll");

add_filter ('the_content', 'myopollcontent');
function myopollcontent($content) {
   global $wp, $wpdb, $post;
     
   ob_start();
	
   if(is_single()) {
   	 $type = get_post_meta($post->ID,'myo-type',true);
   	  if($type == 'facebook'){
   	  echo do_shortcode("[myo_fb_poll poll = $post->ID ]");	
	  add_thickbox();
   	  }elseif($type == 'box' || $type == 'bar'){
      echo do_shortcode("[myo_poll poll = $post->ID ]");
      }elseif($type == 'buddypress'){
      echo do_shortcode("[myo_bp_poll poll = $post->ID ]");		
      }
   }
   $content .= ob_get_contents();
    ob_end_clean();
   return $content;
}



add_filter( 'manage_edit-myo_polling_columns', 'my_edit_myo_polling_columns' ) ;

function my_edit_myo_polling_columns( $columns ) {

    $columns = array(
        'cb' => '<input type="checkbox" />',
        'title' => __( 'Title' ),	
        'id' => __( 'ID'),
        'date' => __( 'Date' )
    );

    return $columns;
}

add_action( 'manage_myo_polling_posts_custom_column', 'my_manage_myo_polling_columns', 10, 2 );

function my_manage_myo_polling_columns( $column, $post_id ) {
    global $post;

    switch( $column ) {

        /* If displaying the 'rating' column. */
   		
			 case 'id' :

            /* Get the post meta. */
            echo $post_id;

            break;


        /* Just break out of the switch statement for everything else. */
default:
            break;
    }
}


//code for manually adding new

add_action( 'add_meta_boxes', 'myo_poll_custom_meta_box' );

function myo_poll_custom_meta_box() {
	
	$post_types=get_post_types('','names'); 
	foreach ($post_types as $post_type ) {
	  add_meta_box( 'myo_polling', 'Easy Polling Options', 'new_poll', $post_type);
	}
}

function new_poll() {
    global $wp, $wpdb, $post;

    // Noncename needed to verify where the data originated
    echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
    wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
    // Get the location data if its already been entered
   $poll_options = get_post_meta($post->ID,'myo-poll-options',true);
   if($poll_options == NULL){
   	$poll_options = 2;
   }

   $options = get_post_meta($post->ID,'myo-options',true);
   $votes = get_post_meta($post->ID,'myo-votes',true);
   $colors = get_post_meta($post->ID,'myo-colors',true);
   $type = get_post_meta($post->ID,'myo-type',true);
   $display = get_post_meta($post->ID,'myo-display',true);
   $myo_title = get_post_meta($post->ID,'myo-title',true);

   if($options != NULL){
	$option_array = explode(",",$options);
   }
   if($votes != NULL){
  	$votes_array = explode(",",$votes);
   }
 

   if($colors != NULL){
   	$colors_array = explode(",",$colors);
   }
   
   
    ?>

    <div id = 'myo-poll-options'>
    <div id="picker" style="float: right;"></div>  
    <?php 
    $i = 0;
    while($i < $poll_options){ ?>	
	    <?php 
	        if($options == NULL){
	    	        $value = "";
	        }else{
	   		$value = $option_array[$i]; 
		}
		if($votes == NULL){
			$votes = 0;
		}else{
			$votes = $votes_array[$i];
		}
		if($colors == NULL){
			$colorsv = '#edfa00';
		}else{
			$colorsv = $colors_array[$i];
		}
		
    ?>
    
	<?php 
	$j = $i+1;
	echo "<br/><label>Option $j: </label><input type='text' class = 'myo-option' name='option-$i' value= '$value' data-myo-option = '$i'  />"; 
	echo "<label for='color$j'>Color $j:</label><input type='text' id='color$i' name='color$i' class='colorwell' value='$colorsv' />"; 
	$i = $i + 1;
	} 
	?>
	
	</div>
	
		<br/><br/>
<div class = "button-primary" href="#" title="Add Option" id = "myo-add-option" style = "width:10%;text-align:center">Add Option</div>
	<br/>
	
	<?php if($type == 'bar'){ ?>
	<label> Type of Poll</label>
	<br/>
	<select name = "myo-type">
	  <option value="box">Box</option>
	  <option value="bar" selected>Bar</option>
	  <?php do_action('myo_style'); ?>
	  <?php do_action('myo_bp_style'); ?>
	</select>
	<?php }elseif($type == 'facebook'){ ?>
	<label> Type of Poll</label>
	<br/>
	<select name = "myo-type">
	  <option value="box">Box</option>
	  <option value="bar">Bar</option>
	  <?php do_action('myo_style2'); ?>
	  <?php do_action('myo_bp_style'); ?>
	</select>
	<br/><br/>
	<?php }elseif($type == 'buddypress'){ ?>
	<label> Type of Poll</label>
	<br/>
	<select name = "myo-type">
	  <option value="box">Box</option>
	  <option value="bar">Bar</option>
	  <?php do_action('myo_style'); ?>
	  <?php do_action('myo_bp_style2'); ?>
	</select>
	<br/><br/>	
	<?php }else{ ?>
	<label> Type of Poll</label>
	<br/>
	<select name = "myo-type">
	  <option value="box" selected>Box</option>
	  <option value="bar">Bar</option>
	  <?php do_action('myo_style'); ?>
	  <?php do_action('myo_bp_style'); ?>
	</select>
	<br/><br/>
		
	<?php } ?>
	<label>Display type (show number of votes or percentage)</label>
	<br/>
	<?php if($display == 'votes'){ ?>
	<select name = "myo-display">
	  <option value="perc">Percentage</option>
	  <option value="votes" selected>Votes</option>
	</select>
	<br/>
	<label>Display type (show number of votes or percentage)</label>
	<br/>
	<?php }else{ ?>
	<select name = "myo-display">
	  <option value="perc" selected>Percentage</option>
	  <option value="votes">Votes</option>
	</select>
	<?php } ?>
	<br/>
	<label>Show the post title above the poll</label>
	<?php if($myo_title == 'yes'){ ?>
	<select name = "myo-title">
	  <option value="yes" selected>Yes</option>
	  <option value="no">No</option>
	</select>
	<br/>
	<br/>
	<?php }else{ ?>
	<select name = "myo-title">
	  <option value="yes">Yes</option>
	  <option value="no" selected>No</option>
	</select>
	<?php } ?>
	
	
	<input type = "hidden" name = "myo-options" id = "myo-options" value = "<?php echo $i; ?>" />



<div style="clear:both"></div> 



<?php
}


// Save the Metabox Data
function wpt_save_new_poll($post_id, $post) {

     global $wp, $wpdb;  

    // verify this came from the our screen and with proper authorization,
    // because save_post can be triggered at other times
    if( !isset($_POST['eventmeta_noncename'])){
     return $post->ID;
    }
    if (  !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
    return $post->ID;
    }
    
	$votes = get_post_meta($post->ID,'myo-votes',true);
	$colors = get_post_meta($post->ID,'myo-colors',true);
	
	
    // Is the user allowed to edit the post or page?
    if ( !current_user_can( 'edit_post', $post->ID ))
        return $post->ID;
    // OK, we're authenticated: we need to find and save the data
	$options	 = 		$_POST['myo-options'];
	$type 		 = 		$_POST['myo-type'];
	$display 	 = 		$_POST['myo-display'];
	$mtitle		 =		$_POST['myo-title'];	
	
	update_post_meta($post->ID,'myo-type',$type);
	update_post_meta($post->ID,'myo-display',$display);
	update_post_meta($post->ID,'myo-title',$mtitle);
	
	$i = 0;
	$str = array();
	$vts = array();
	
	if($votes != NULL){
		$vts = explode(",",$votes);
	}
	if($colors != NULL){
		$cls = explode(",",$colors);
	}
	
	while($i < $options){
		$str[$i] = sanitize_text_field($_POST['option-' . $i]);
		if(!isset($vts[$i])){
			$vts[$i] = 0;
		}
		$cls[$i] = sanitize_text_field($_POST['color' . $i]);

	$i++;
	}
	$csv = implode(",",$str);
	$votes = implode(",",$vts);
	$colors = implode(",",$cls);
    update_post_meta($post->ID,'myo-options',$csv);
	update_post_meta($post->ID,'myo-poll-options',(int)$_POST['myo-options']);
	update_post_meta($post->ID,'myo-votes',$votes);
	update_post_meta($post->ID,'myo-colors',$colors);
    

    
}
add_action('save_post', 'wpt_save_new_poll', 1, 2); // save the custom fields


//new code for autoupdating and regCheck
#} Send registration info to my server
function polling_sendReg($e='',$na='',$pl=''){

			global $myo_polling_urls;	
			if( function_exists('curl_init') ) { 
					$postData = array('ori'=>get_site_url());
					$postData['e'] = $e; //email
					$postData['na'] = $na;  //name
					$postData['pl'] = $pl;  //plugin

					
					$fields = ''; foreach($postData as $key => $value) $fields .= $key . '=' . $value . '&'; rtrim($fields, '&');
					$ch = curl_init($myo_polling_urls['regCheck']);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_setopt($ch, CURLOPT_HEADER, 0);
					curl_setopt($ch, CURLOPT_POST, count($postData));
					curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
					curl_setopt($ch, CURLOPT_TIMEOUT, 10);
					$regDets = curl_exec($ch);
					
					curl_close($ch);
					return $regDets;
			} # else, cry?			
			return  $false;
}


//code for the warnings and auto updating
global $myo_polling_urls;
$api_url = $myo_polling_urls['updateCheck'];
$plugin_slug = basename(dirname(__FILE__));


// Take over the update check
add_filter('pre_set_site_transient_update_plugins', 'polling_check_for_plugin_update');

function polling_check_for_plugin_update($checked_data) {
	global $api_url, $plugin_slug;

	//Comment out these two lines during testing.
	if (empty($checked_data->checked))
		return $checked_data;

	$args = array(
		'slug' => $plugin_slug,
		'version' => $checked_data->checked[$plugin_slug .'/'. $plugin_slug .'.php'],
	);
	$request_string = array(
			'body' => array(
				'action' => 'basic_check', 
				'request' => serialize($args),
				'api-key' => md5(get_bloginfo('url'))
			),
			'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
		);

	// Start checking for an update
	$raw_response = wp_remote_post($api_url, $request_string);

	if (!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
		$response = unserialize($raw_response['body']);

	if (is_object($response) && !empty($response)) // Feed the update data into WP updater
		$checked_data->response[$plugin_slug .'/'. $plugin_slug .'.php'] = $response;

	return $checked_data;
}



add_filter('plugins_api', 'polling_plugin_api_call', 10, 3);

function  polling_plugin_api_call($def, $action, $args) {
	global $plugin_slug, $api_url;

	if ($args->slug != $plugin_slug)
		return false;

	// Get the current version
	$plugin_info = get_site_transient('update_plugins');
	$current_version = $plugin_info->checked[$plugin_slug .'/'. $plugin_slug .'.php'];
	$args->version = $current_version;

	$request_string = array(
			'body' => array(
				'action' => $action, 
				'request' => serialize($args),
				'api-key' => md5(get_bloginfo('url'))
			),
			'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url')
		);

	$request = wp_remote_post($api_url, $request_string);

	if (is_wp_error($request)) {
		$res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>'), $request->get_error_message());
	} else {
		$res = unserialize($request['body']);

		if ($res === false)
			$res = new WP_Error('plugins_api_failed', __('An unknown error occurred'), $request['body']);
	}

	return $res;
}



